import youtube_dl
import time
import shutil
import movefile
import json
from os import rename

class VideoGet(object):
	"""使用youtube-dl下载视频"""
	def __init__(self, savepath):
		super(VideoGet, self).__init__()
		self.urls = movefile.readLines()
		if savepath.split('/')[-1] == '':
			self.savepath = savepath
		else:
			self.savepath = savepath+"/"

	def ydl_opts(self):
		# savepath = "/Users/jl/Desktop/Test"
		# title = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
		# 'outtmpl' : savepath+"/"+title+'.%(ext)s' , 输出目录
		# 'writeinfojson': 'true`', 是否输出info文件
		# --no-check-certificate
		opts = {
			'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
			'recode_video' :'mp4',
			'merge_output_format': 'mp4',
			'ignoreerrors': 'true',
			'nocheckcertificate':'true',
			# 'logger': MyLogger(),
			'progress_hooks': [self.vget_hook]
		}
		return opts

	def vget_hook(self,d):
		if d['status'] == 'downloading':
			pass
			# info = 'bytes: ' + str(d['downloaded_bytes']) + ', elapsed: ' + str(
			# 	d['elapsed']) + ', speed: ' + str(d['speed']) + ', filename: ' + d['filename'];
			# print(info)
		elif d['status'] == 'finished':
			filename = d['filename'].split("/")[-1]
			targetPath = self.savepath+filename
			movefile.movefile(filename,targetPath)
			print('下载完成')

	def download(self):
		# 打印日志
		with youtube_dl.YoutubeDL(self.ydl_opts()) as ydl:
			# 下载给定的URL列表
			result = ydl.download(self.urls)

	def video_info(self):
		with youtube_dl.YoutubeDL(self.ydl_opts()) as ydl:
			# extract_info 提取信息
			result = ydl.extract_info(self.urls, download=False)
			print(json.dumps(result['entries']))
			print(type(result))
	
	def selfurls(self):
		print(self.urls)
		
if __name__ == "__main__":
	savepath = "/Users/jl/Desktop/Test"
	vget = VideoGet(savepath)
	vget.download()








